

<template>
  <div class="outfit-recommend">
    <!-- 页面头部 -->
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <div class="header-content">
          <h1>💼 智能穿搭推荐系统</h1>
          <p>基于AI的个性化穿搭建议，让您的穿搭更加出众</p>
        </div>
      </template>
      
      <template #extra>
        <div class="header-actions">
          <el-button type="primary" @click="goToUserManagement">
            👥 用户管理
          </el-button>
          <el-button @click="handleShowHelp">
            ❓ 使用帮助
          </el-button>
        </div>
      </template>
    </el-page-header>

    <!-- 主体内容区 -->
    <div class="page-content">
      <div class="chat-layout">
        <!-- 历史对话列表侧边栏 -->
        <div class="conversation-sidebar">
          <div class="sidebar-header">
            <h3>💬 对话历史</h3>
            <el-button
              type="text"
              size="small"
              @click="handleClearAllHistory"
              :disabled="!hasHistory || isLoading"
            >
              🗑️ 清空全部
            </el-button>
          </div>
          
          <div class="conversation-list">
            <div
              v-for="(conversation, index) in conversationHistory"
              :key="index"
              class="conversation-item"
              :class="{ active: currentConversationIndex === index }"
              @click="switchConversation(index)"
            >
              <div class="conversation-info">
                <div class="conversation-title">
                  {{ conversation.title || `对话 ${index + 1}` }}
                </div>
                <div class="conversation-meta">
                  <span class="username">{{ conversation.username || '未知用户' }}</span>
                  <span class="time">{{ formatTime(conversation.lastTime) }}</span>
                </div>
              </div>
              <div class="conversation-actions">
                <el-button
                  type="text"
                  size="small"
                  @click.stop="deleteConversation(index)"
                  class="delete-btn"
                >
                  🗑️
                </el-button>
              </div>
            </div>
            
            <div v-if="conversationHistory.length === 0" class="empty-state">
              <div class="empty-icon">💬</div>
              <div class="empty-text">暂无对话历史</div>
              <div class="empty-hint">开始新的对话吧！</div>
            </div>
          </div>
        </div>
        
        <!-- 主对话区域 -->
        <div class="chat-main">
          <QueryInput :history-count="chatListLength" />
          <ChatHistory ref="chatHistoryRef" />
        </div>
      </div>
    </div>

    <!-- 帮助弹窗 -->
    <el-dialog
      v-model="helpDialogVisible"
      title="💡 使用帮助"
      width="800px"
      class="help-dialog"
    >
      <div class="help-content">
        <div class="help-section">
          <h4>🎯 系统功能</h4>
          <p>本系统基于AI技术，能够根据用户信息提供个性化的穿搭建议。支持多轮对话，让AI更好地理解您的需求。</p>
        </div>
        
        <div class="help-section">
          <h4>📝 输入格式</h4>
          <p>您可以使用自然语言描述您的需求，例如：</p>
          <ul>
            <li>"为小明推荐职场通勤穿搭"</li>
            <li>"我是小红，想要约会穿搭建议"</li>
            <li>"给张三推荐运动风格的衣服"</li>
          </ul>
        </div>
        
        <div class="help-section">
          <h4>👤 用户信息</h4>
          <p>系统会根据以下信息为您推荐合适的穿搭：</p>
          <el-table :data="userInfoList" border stripe>
            <el-table-column prop="name" label="信息类型" width="120" />
            <el-table-column prop="desc" label="说明" />
          </el-table>
        </div>
        
        <div class="help-section">
          <h4>💡 使用技巧</h4>
          <ul>
            <li>提供越详细的个人信息，推荐越精准</li>
            <li>可以多次对话，让AI更了解您的偏好</li>
            <li>支持中文和英文输入</li>
            <li>对话历史会自动保存，方便下次查看</li>
          </ul>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="helpDialogVisible = false">知道了</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElPageHeader, ElDialog, ElTag, ElTable, ElTableColumn, ElMessage, ElButton } from 'element-plus'
import QueryInput from '../components/QueryInput.vue'
import ChatHistory from '../components/ChatHistory.vue'
import eventBus from '../utils/eventBus.js'

// 响应式数据
const helpDialogVisible = ref(false)
const chatHistoryRef = ref(null)
const isLoading = ref(false)
const chatList = ref([])
const chatListLength = computed(() => chatList.value.length)
const hasHistory = computed(() => chatList.value.length > 0)
const currentUsername = ref('')

// 对话历史管理
const conversationHistory = ref([])
const currentConversationIndex = ref(-1)
const currentConversationId = ref(null)

// 用户信息列表
const userInfoList = ref([
  { name: '姓名', desc: '用于匹配系统中的用户信息' },
  { name: '性别', desc: '影响穿搭风格（如男士休闲、女士通勤）' },
  { name: '年龄', desc: '适配年龄层审美（如学生党、职场中年）' },
  { name: '身高/体重', desc: '推荐合身的版型（如修身、宽松）' },
  { name: '爱好', desc: '结合兴趣推荐（如运动爱好者推荐速干衣）' },
  { name: '行为习惯', desc: '适配日常场景（如久坐办公推荐舒适面料）' }
])

// 方法
const handleShowHelp = () => {
  helpDialogVisible.value = true
}

const syncChatListLength = () => {
  if (chatHistoryRef.value && chatHistoryRef.value.chatList) {
    chatList.value = chatHistoryRef.value.chatList
  }
}

// 对话历史管理方法
const createNewConversation = (username, query) => {
  const conversation = {
    id: Date.now().toString(),
    username: username,
    title: query.substring(0, 30) + (query.length > 30 ? '...' : ''),
    lastTime: new Date(),
    messages: []
  }
  
  conversationHistory.value.unshift(conversation)
  currentConversationIndex.value = 0
  currentConversationId.value = conversation.id
  
  // 保存到本地存储
  saveConversationsToStorage()
}

const switchConversation = (index) => {
  if (index === currentConversationIndex.value) return
  
  // 保存当前对话
  if (currentConversationIndex.value >= 0) {
    saveCurrentConversation()
  }
  
  // 切换到新对话
  currentConversationIndex.value = index
  currentConversationId.value = conversationHistory.value[index].id
  
  // 加载对话内容
  loadConversation(index)
}

const deleteConversation = (index) => {
  ElMessage.confirm('确定要删除这个对话吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    conversationHistory.value.splice(index, 1)
    
    // 如果删除的是当前对话，切换到第一个对话
    if (index === currentConversationIndex.value) {
      if (conversationHistory.value.length > 0) {
        currentConversationIndex.value = 0
        currentConversationId.value = conversationHistory.value[0].id
        loadConversation(0)
      } else {
        currentConversationIndex.value = -1
        currentConversationId.value = null
        // 清空聊天历史
        eventBus.emit('clear-history')
      }
    } else if (index < currentConversationIndex.value) {
      currentConversationIndex.value--
    }
    
    saveConversationsToStorage()
    ElMessage.success('对话已删除')
  })
}

const handleClearAllHistory = () => {
  ElMessage.confirm('确定要清空所有对话历史吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    conversationHistory.value = []
    currentConversationIndex.value = -1
    currentConversationId.value = null
    eventBus.emit('clear-history')
    saveConversationsToStorage()
    ElMessage.success('所有对话历史已清空')
  })
}

const saveCurrentConversation = () => {
  if (currentConversationIndex.value >= 0 && chatHistoryRef.value) {
    const currentConv = conversationHistory.value[currentConversationIndex.value]
    currentConv.messages = [...chatHistoryRef.value.chatList]
    currentConv.lastTime = new Date()
    currentConv.title = generateConversationTitle(currentConv.messages)
  }
}

const loadConversation = (index) => {
  const conversation = conversationHistory.value[index]
  if (conversation && conversation.messages) {
    // 清空当前聊天历史
    eventBus.emit('clear-history')
    
    // 加载对话消息
    setTimeout(() => {
      conversation.messages.forEach(msg => {
        if (msg.role === 'user') {
          eventBus.emit('add-user-message', msg)
        } else if (msg.role === 'ai') {
          eventBus.emit('add-ai-message-chunk', msg.content)
          eventBus.emit('ai-response-complete', msg.meta || {})
        }
      })
    }, 100)
  }
}

const generateConversationTitle = (messages) => {
  if (messages.length === 0) return '新对话'
  
  const firstUserMsg = messages.find(msg => msg.role === 'user')
  if (firstUserMsg) {
    return firstUserMsg.content.substring(0, 30) + (firstUserMsg.content.length > 30 ? '...' : '')
  }
  
  return '新对话'
}

const formatTime = (time) => {
  if (!time) return ''
  
  const now = new Date()
  const diff = now - new Date(time)
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return new Date(time).toLocaleDateString()
}

// 本地存储
const saveConversationsToStorage = () => {
  try {
    localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory.value))
  } catch (error) {
    console.error('保存对话历史失败:', error)
  }
}

const loadConversationsFromStorage = () => {
  try {
    const stored = localStorage.getItem('conversationHistory')
    if (stored) {
      conversationHistory.value = JSON.parse(stored)
      // 恢复时间对象
      conversationHistory.value.forEach(conv => {
        conv.lastTime = new Date(conv.lastTime)
      })
    }
  } catch (error) {
    console.error('加载对话历史失败:', error)
  }
}

// 事件监听
const handleUserQuerySubmitted = (data) => {
  console.log('收到用户查询:', data)
  
  let username = ''
  if (typeof data === 'object' && data.username) {
    username = data.username
  } else if (typeof data === 'string') {
    username = extractUsernameFromQuery(data)
  }
  
  if (username) {
    currentUsername.value = username
    
    // 检查是否已有该用户的对话
    const existingIndex = conversationHistory.value.findIndex(
      conv => conv.username === username
    )
    
    if (existingIndex >= 0) {
      // 切换到现有对话
      switchConversation(existingIndex)
    } else {
      // 创建新对话
      createNewConversation(username, data.query || data)
    }
  }
}

const extractUsernameFromQuery = (query) => {
  if (typeof query !== 'string') return ''
  
  // 支持多种用户名提取模式
  const patterns = [
    /为([\u4e00-\u9fa5a-zA-Z0-9_]+)/,
    /我是([\u4e00-\u9fa5a-zA-Z0-9_]+)/,
    /我叫([\u4e00-\u9fa5a-zA-Z0-9_]+)/,
    /给([\u4e00-\u9fa5a-zA-Z0-9_]+)/,
    /([\u4e00-\u9fa5a-zA-Z0-9_]+)的穿搭/
  ]
  
  for (const pattern of patterns) {
    const match = query.match(pattern)
    if (match) {
      return match[1]
    }
  }
  
  return ''
}

// 跳转到用户管理页面
const goToUserManagement = () => {
  window.location.href = '/user-management'
}

// 返回上一页
const goBack = () => {
  window.history.back()
}

// 生命周期
onMounted(() => {
  // 加载对话历史
  loadConversationsFromStorage()
  
  // 监听事件
  eventBus.on('user-query-submitted', handleUserQuerySubmitted)
  eventBus.on('add-user-message', syncChatListLength)
  eventBus.on('add-ai-message-chunk', syncChatListLength)
  eventBus.on('ai-response-complete', syncChatListLength)
  eventBus.on('ai-response-error', syncChatListLength)
  eventBus.on('clear-history', syncChatListLength)
  
  // 同步聊天列表长度
  syncChatListLength()
})

onUnmounted(() => {
  // 保存当前对话
  saveCurrentConversation()
  saveConversationsToStorage()
  
  // 移除事件监听
  eventBus.off('user-query-submitted', handleUserQuerySubmitted)
  eventBus.off('add-user-message', syncChatListLength)
  eventBus.off('add-ai-message-chunk', syncChatListLength)
  eventBus.off('ai-response-complete', syncChatListLength)
  eventBus.off('ai-response-error', syncChatListLength)
  eventBus.off('clear-history', syncChatListLength)
})
</script>

<style scoped>
.outfit-recommend {
  min-height: 100vh;
  padding: 24px;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 24px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 16px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-content {
  margin-bottom: 120px; /* 为浮动输入框留出空间 */
}

.chat-layout {
  display: flex;
  gap: 24px;
  height: calc(100vh - 200px);
}

.conversation-sidebar {
  width: 300px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.conversation-item {
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  margin-bottom: 12px;
}

.conversation-item:hover {
  background: #f8f9fa;
  border-color: #e9ecef;
}

.conversation-item.active {
  background: #e3f2fd;
  border-color: #2196f3;
}

.conversation-info {
  flex: 1;
}

.conversation-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.conversation-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.username {
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 12px;
  color: #333;
}

.time {
  color: #999;
}

.conversation-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #ff4d4f;
  padding: 4px 8px;
  font-size: 12px;
}

.delete-btn:hover {
  background: #fff1f0;
  color: #ff4d4f;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 8px;
  color: #666;
}

.empty-hint {
  font-size: 14px;
  color: #999;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.help-dialog {
  border-radius: 12px;
}

.help-content {
  line-height: 1.8;
}

.help-section {
  margin-bottom: 24px;
}

.help-section:last-child {
  margin-bottom: 0;
}

.help-section h4 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.help-section p {
  margin: 0 0 12px 0;
  color: #6b7280;
}

.help-section ul {
  margin: 0 0 12px 0;
  padding-left: 20px;
  color: #6b7280;
}

.help-section li {
  margin-bottom: 8px;
}

@media (max-width: 1024px) {
  .chat-layout {
    flex-direction: column;
    height: auto;
  }
  
  .conversation-sidebar {
    width: 100%;
    max-height: 300px;
  }
}

@media (max-width: 768px) {
  .outfit-recommend {
    padding: 12px;
  }
  
  .page-header {
    padding: 16px;
  }
  
  .header-content h1 {
    font-size: 24px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .conversation-sidebar {
    width: 100%;
    max-height: 250px;
  }
}
</style>
